package com.wocai.jrt.im;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vteba.utils.common.PropUtils;

public class ImSdk {
	private static final Logger LOGGER = LoggerFactory.getLogger(ImSdk.class);
	private static final int TIMEOUT = 10 * 1000;
	private static HttpHost httpHost = null;
	private static Map<String, String> params;

	static {
		String hostName = PropUtils.get("im.hostName");
		int port = PropUtils.getInt("im.port");
		String schema = PropUtils.get("im.schema");
		httpHost = new HttpHost(hostName, port, schema);
		
		String sdkappid = PropUtils.get("im.sdkAppId");
		String identifier = PropUtils.get("im.identifier");
		String usersig = null;
		try {
			usersig = SigUtils.getSig(identifier);
		} catch (Exception e) {
			LOGGER.error("签名错误！");
			e.printStackTrace();
		}
		params = new HashMap<String, String>();
		params.put("usersig", usersig);
		params.put("identifier", identifier);
		params.put("sdkappid", sdkappid);
		params.put("contenttype", "json");
	}

	public static String send(String json, String api) {
		HttpPost post = buildHttpPost(json, api);
		byte[] bytes = resolve(post, 1);
		String result = new String(bytes);
		LOGGER.info(result);
		return result;
	}

	private static byte[] resolve(final HttpPost httpPost, int type) {
		byte[] bytes = null;
		try {
			HttpHost host = null;
			if (type == 1) {
				host = httpHost;
			}
			// 创建客户端
			CloseableHttpClient httpClient = HttpClientBuilder.create().build();
			// 发起调用
			CloseableHttpResponse httpResponse = httpClient.execute(host, httpPost);
			int status = httpResponse.getStatusLine().getStatusCode();
			if (status == 200) {// 结果正常
				bytes = EntityUtils.toByteArray(httpResponse.getEntity());
			} else {// 结果异常
				LOGGER.error("请求的urlPath错误[{}]，响应码是[{}]", httpPost.getURI().toString(), status);
			}
			httpResponse.close();
			httpClient.close();
		} catch (ClientProtocolException e) {
			LOGGER.error("[{}]请求，客户端协议错误。", httpPost.getURI().toString(), e.getMessage());
		} catch (IOException e) {
			LOGGER.error("[{}]请求IO错误。", httpPost.getURI().toString(), e);
		}
		return bytes;
	}

	private static HttpPost buildHttpPost(final String json, final String api) {
		// 构建请求uri
		URI uri = null;
		try {
			URIBuilder uriBuilder = new URIBuilder();
			// 设置参数
			for (Entry<String, String> entry : params.entrySet()) {
				uriBuilder.setParameter(entry.getKey(), entry.getValue());
			}
			// 设置请求的路径
			uriBuilder.setPath(api);
			uri = uriBuilder.build();
		} catch (URISyntaxException e1) {
			LOGGER.error("HttpClient创建URI错误。可能传递的参数错误。", e1.getMessage());
			return null;
		}

		// 设置post请求
		HttpPost httpPost = new HttpPost(uri);
		try {
			StringEntity stringEntity = new StringEntity(json);
			stringEntity.setContentEncoding("UTF-8");
			stringEntity.setContentType("application/json");
			httpPost.setEntity(stringEntity);
		} catch (UnsupportedEncodingException e) {
			LOGGER.error("HttpClient创建Entity错误。", e.getMessage());
			return null;
		}

		RequestConfig config = RequestConfig.custom().setSocketTimeout(TIMEOUT)
				.setConnectTimeout(TIMEOUT).build();
		httpPost.setConfig(config);
		return httpPost;
	}
	
	
	
	public static void main(String[] args) {
		//导入
		String json = "{\"Identifier\":\"56b1bff6d4c6f0261d8441c9\",\"Nick\":\"admin\",\"FaceUrl\":\"\"}";
		String api = "/v4/im_open_login_svc/account_import";
		System.out.println(send(json, api ));
		//拉取
		json = "{\"To_Account\":[\"56b1bff6d4c6f0261d8441c9\"],\"TagList\":[\"Tag_Profile_IM_Nick\"]}";
		api = "/v4/profile/portrait_get";
		System.out.println(send(json, api ));
//		
//		Map<String, Object> jsonMap = new HashMap<String, Object>();
//		jsonMap.put("Identifier", "5639712d24a385059ed59dd");
//		jsonMap.put("Nick", "大马哥");
//		jsonMap.put("FaceUrl","");
//		List<UserBean> userBeans = new ArrayList<UserBean>();
//		UserBean user = new UserBean();
//		user.setFaceUrl("asdfasdf");
//		user.setNick("asdfasdf");
//		user.setIdentifier("sdafasdfsad");
//		userBeans.add(user);
//		UserBean user2 = new UserBean();
//		userBeans.add(user2);
//		jsonMap.put("user", userBeans);
//		System.out.println(FastJsonUtils.toJson(jsonMap));
	}
}
